<template>
<!--面包屑-->
<div style="margin-bottom: 30px">
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>
      <router-link to="/MenuModule/MenuDisplay">菜单管理</router-link>
    </el-breadcrumb-item>
    <el-breadcrumb-item>分配角色权限</el-breadcrumb-item>
  </el-breadcrumb>
</div>


  <div class="common-layout">
    <el-container>
      <el-aside width="300px">
        <!-- <el-tree ref="ruleFormRef" style="max-width: 300px" :default-expand-all="true" :data="TreeData" show-checkbox node-key="id" :default-checked-keys="defaultCheck"  @check-change="handleCheckChange" :props="defaultProps"/> -->

        <el-tree style="max-width: 600px" :data="TreeData" show-checkbox node-key="value" :default-expand-all="true" @check-change="handleCheckChange"  :default-checked-keys="defaultCheck" :props="defaultProps"/>
      </el-aside>

      <el-main>
        <el-form ref="ruleFormRefTwo" style="max-width: 600px;margin: auto;" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="角色ID" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择角色" style="width: 100%;" @change="BackMenuTree" clearable>
            <el-option v-for="item in roleData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRefTwo)">提交</el-button>
          <el-button type="primary" @click="UpdateRoleMenu">修改</el-button>
        </el-form-item>
        </el-form>
      </el-main>

    </el-container>
  </div>


</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ElTree } from 'element-plus'
import {useRoute,useRouter} from 'vue-router'
import type Node from 'element-plus/es/components/tree/src/model/node'

const route = useRoute();
const router = useRouter();
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleFormRefTwo = ref<FormInstance>()
  const treeRef = ref<InstanceType<typeof ElTree>>()

const form: any = reactive({
  roleId:'',
  menuId    : [],
  menufunction: "",
})

onMounted(() => {
  getTreeList()

  getRoleList()
})

interface Tree {
  id: number
  label: string
  children?: Tree[]
}

const defaultProps = {
  children: 'children',
  label: 'label',
}


const roleMenuIds:any=[]
const getCheckedKeys = () => {
  
  console.log(treeRef.value!.getCheckedKeys(false))
  roleMenuIds.value = treeRef.value!.getCheckedKeys(false)
}

// const handleCheckChange = (data:any, checked:any) => {
//   // 检查节点是否有子集
//   if (data.children && data.children.length > 0) {
//     // 检查子集节点的选中状态
//     const allChildrenChecked = data.children.every((child:any) => child.checked);
//     data.checked = allChildrenChecked;
//   }
//   console.log(data.checked);

//   // 这里可以添加更多逻辑来处理选中状态的更新
// };


//判断是否选中
let menu:any=ref([])
const handleCheckChange = (data: any, checked: any) => {
 
  if (checked) {
    menu.value.push(data.value)
  //console.log(data.value)
  // console.log(form.menuId);
  }
  else{
    menu.value= menu.value.filter((item:any) => item !== data.value)
  }
  form.menuId=menu.value;
console.log(form.menuId)
}

//树形
const TreeData: any = ref([])
//默认展开
const treeInfoData:any=ref([])
const getTreeList =()=>{
  axios.get('http://1.117.93.87:8000/rbacdu/api/Menu/MenuTreeShow').then(res=>{
    console.log(res);
    TreeData.value = res.data.data;
    console.log(TreeData.value);
    treeInfoData.value = res.data.data.map((x: any) => x.value)
    console.log(TreeData.value);
    console.log(treeInfoData.value);
    
  }).catch(err=>{
    console.log(err);
    
  })    
}

//校验
const rules = reactive<FormRules>({
  roleId: [
    { required: true, message: '请选择角色', trigger: 'blur' },
  ],
})

//角色下拉框
const roleData:any=ref([])
const getRoleList=()=>{
  axios.get('http://1.117.93.87:8000/rbacdu/api/Role/RoleSelectShow').then(res=>{
    //console.log(res);
    roleData.value=res.data.data;
  }).catch(err=>{
    console.log(err);
    
  })    
}


//提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let CharacterMenuAdd = {
        roleId:form.roleId,
        menuId: form.menuId
      }
      axios.post('http://1.117.93.87:8000/rbacxie/api/Menu/RoleMenu',CharacterMenuAdd).then(res => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage.success("创建成功!")
          window.location.reload()
        } else {
          ElMessage.error("创建失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    } else {
      console.log('error submit!', fields)
    }
  })
}


//反弹菜单树形
//反填选中
const defaultCheck:any=ref([])
const BackMenuTree = () => {
  axios.get('http://1.117.93.87:8000/rbacdu/api/RoleMenuFun/RoleMenuFunByRoleId', {
    params: {
      roleId: form.roleId
    }
  }).then(res=>{
    console.log(res);
    let check = res.data.data;
    //console.log(check);
    
    defaultCheck.value = res.data.data;
    console.log(defaultCheck.value);
    
  }).catch(err=>{
    console.log(err);
    
  })  
}

//修改菜单树形
const UpdateRoleMenu = () => {
  let CharacterMenuUpdate = {
    roleId: form.roleId,
    menuId: form.menuId
  }
  axios.put('http://1.117.93.87:8000/rbacxie/api/Menu/RoleMenuUpdate', CharacterMenuUpdate).then(res => {
    console.log(res);
    if (res.data.code == 200) {
      ElMessage.success("修改成功!")
      window.location.reload()
    } else {
      ElMessage.error("修改失败!")
      return
    }
  }).catch(err => {
    console.log(err);

  })
}

</script>

<style scoped>

</style>